package com.gome.transactiontree.recovery;

import com.gome.transactiontree.api.Transaction;
import com.gome.transactiontree.api.TransactionRepository;
import com.gome.transactiontree.logging.TransactionLogger;
import com.gome.transactiontree.serializer.KryoThreadLocalSerializer;
import com.gome.transactiontree.serializer.ObjectSerializer;


public class DefaultRemoteTransactionRecoveryClient implements RemoteTransactionRecoveryClient {
	
	private ObjectSerializer<Transaction> serializer = new KryoThreadLocalSerializer<Transaction>();
	private TransactionRepository transactionRepository = null;

	@Override
	public boolean recover(byte[] transactionBytes) {
		if (transactionBytes == null) {
			return false;
		}
		
		Transaction transaction = serializer.deserialize(transactionBytes);
		String transactionId = transaction.getXid().getTransactionId();
		try {
			int currentyRecoveryNum = transaction.incrRecoveryNum();
			transactionRepository.update(transaction);
			
			TransactionLogger.RECOVERY.info("远程第{}次恢复事务, Transaction={}", currentyRecoveryNum, transaction);
			
			transaction.recover();
			
			transactionRepository.delete(transactionId);
			
			TransactionLogger.RECOVERY.info("远程恢复事务成功, Transaction={}", transaction);
			
			return true;
		} catch (RuntimeException e) {
			TransactionLogger.RECOVERY.error("远程事务恢复错误，Transaction=" + transaction, e);
			return false;
		}
	}

	public TransactionRepository getTransactionRepository() {
		return transactionRepository;
	}

	public void setTransactionRepository(TransactionRepository transactionRepository) {
		this.transactionRepository = transactionRepository;
	}
}